home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9973 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Pointer to int
  5. Date: Thu, 14 Mar 96 18:57:10 GMT
  6. Organization: none
  7. Distribution: world
  8. Message-ID: <826829830snz@genesis.demon.co.uk>
  9. References: <4i76vf$58v@dunlop.cs.strath.ac.uk>
  10. Reply-To: fred@genesis.demon.co.uk
  11. X-NNTP-Posting-Host: genesis.demon.co.uk
  12. X-Newsreader: Demon Internet Simple News v1.27
  13. X-Mail2News-Path: genesis.demon.co.uk
  14.  
  15. In article <4i76vf$58v@dunlop.cs.strath.ac.uk>
  16.            abrown@cs.strath.ac.uk "Andrew Brown" writes:
  17.  
  18. >I have a function that takes as a parameter a pointer to an int. Is it 
  19. >possible to pass the address of a constant directly to the function?
  20.  
  21. No. Pointers need to point to something that in some sense has an address,
  22. in this case an object in memory. A value doesn't exist at a specific memory
  23. address and you can't generate a pointer to one.
  24.  
  25. >eg. 
  26. >  
  27. >If the function is defined as ...
  28. >
  29. >  int function( int * ptr );
  30. >
  31. >could I call it with something like ...
  32. >
  33. >  x = function( &1000 );
  34. >
  35. >where 1000 is the constant to which I want ptr to reference.
  36.  
  37. You can't do this. However you could do something like:
  38.  
  39.    {
  40.        static const int value = 1000;
  41.  
  42.        x = function( &value );
  43.    }
  44.  
  45. The static doesn't change the effect of the program in this case but it
  46. may help the compiler to generate better code. Clearly function() must
  47. never write through the pointer that is its argument and should be declared
  48. as:
  49.  
  50.    int function( const int * ptr );
  51.  
  52. Given this the question is why you pass a pointer to the value rather than
  53. the value itself?
  54.    
  55. -- 
  56. -----------------------------------------
  57. Lawrence Kirby | fred@genesis.demon.co.uk
  58. Wilts, England | 70734.126@compuserve.com
  59. -----------------------------------------
  60.